const Joi = require('@hapi/joi')
const Note = require('../models/note')

exports.v = {
  postNotes: {
    body: Joi.array().items(
      Joi.object().keys({
        id: Joi.object(),
        type: Joi.string().required(),
        position: Joi.object().keys({
          x: Joi.number().min(0).required(),
          y: Joi.number().min(0).required()
        }),
        width: Joi.number().min(0).required(),
        color: Joi.string().required(),
        content: Joi.string()
      })
    )
  }
}

exports.getNotes = async function (ctx, next) {
  var data = await Note.find()
  ctx.body = data
}

exports.postNotes = async function (ctx, next) {
  await Note.deleteMany()
  try {
    for (var item in ctx.request.body) {
      var note = new Note(ctx.request.body[item])
      await note.save()
    }
    ctx.body = {
      success: true,
      message: 'success'
    }
  } catch (err) {
    var details = []
    for (var error in err.errors) {
      details.push(err.errors[error].message)
    }
    ctx.status = 400
    ctx.body = {
      success: false,
      messages: 'invalid data',
      details: details
    }
  }
}
